package com.scs.application.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.modules.sys.entity.Authority;
import com.scs.application.modules.sys.entity.Role;
import com.scs.application.modules.sys.entity.RoleUser;
import com.scs.application.modules.sys.mapper.RoleMapper;
import com.scs.application.modules.sys.service.AuthorityService;
import com.scs.application.modules.sys.service.RoleService;
import com.scs.application.modules.sys.service.RoleUserService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    @Lazy
    RoleUserService roleUserService;
    @Autowired
    @Lazy
    AuthorityService authorityService;

    @Override
    @Transactional
    public Boolean removeRole(List<String> roleIds) {
        for (String roleId : roleIds) {
            // 清除角色权限
            authorityService.remove(new QueryWrapper<Authority>()
                    .eq("target_id", roleId)
                    .eq("target_type", "R"));
            // 清除角色成员
            roleUserService.remove(new QueryWrapper<RoleUser>()
                    .eq("role_id", roleId));
            removeById(roleId);
        }
        return true;
    }

    @Override
    public List<Role> listUserRole(String userId) {
        List<RoleUser> roleUsers = roleUserService.list(new QueryWrapper<RoleUser>()
                .eq("user_id", userId));

        Collection<Role> roles = Lists.newArrayList();
        if (!roleUsers.isEmpty()) {
            Collection<String> roleIds = roleUsers.stream().map(o -> o.getRoleId()).collect(Collectors.toList());
            roles = listByIds(roleIds);
        }

        // 是否包含 everyone用户组
        long count = roles.stream().filter(r -> "everyone".equalsIgnoreCase(r.getCode())).count();
        if (count == 0) {
            Role everyoneRole = this.getOne(new QueryWrapper<Role>().eq("code", "everyone"));
            if (everyoneRole != null) {
                roles.add(everyoneRole);
            }
        }
        return (List<Role>) roles;
    }

}
